package com.webserver.core;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 处理请求的环节
 */
public class DispatchServlet {
     Map<String,String> map = new HashMap<>();
     //表示sources下的static目录，实际是运行时编译后target/classes下的static目录
     private static File staticDir;
     static{
          try {
               staticDir=new File(
                       ClientHandler.class.getClassLoader().getResource(
                               "./static"
                       ).toURI()
               );
          } catch (URISyntaxException e) {
               e.printStackTrace();
          }
     }
     public void service(HttpServletRequest request, HttpServletResponse response){
          //根据用户的请求获取用户所登录的网址（抽象路径）
          String path = request.getUri();
          System.out.println(path);
          //去static目录下根据用户请求的抽象路径定位下面的文件
          File file = new File(staticDir,path);
          if(file.isFile()){//判断确实是个文件
               response.setContentFile(file);
               response.addHeader("Content-Type", contentType//获取后缀名
                       (String.valueOf(file.getName().split("\\.")[
                               Integer.parseInt(String.valueOf(file.getName().split("\\.").length))-1
                               ])));
               response.addHeader("Content-Length",String.valueOf(file.length()));
          }else{//文件不存在或为目录
               response.setStatusCode(404);
               response.setStatusReason("Not Found");
               file = new File(staticDir,"/root/404.html");
               response.setContentFile(file);
               response.addHeader("Content-Type","text/html");
               response.addHeader("Content-Length",String.valueOf(file.length()));
          }
     }
     public String contentType(String type){
          map.put("html","text/html");
          map.put("text","text/css");
          map.put("application","application/javascript");
          map.put("png","image/png");
          map.put("gif","image/gif");
          map.put("jpg","image/jpeg");
          String content = map.get(type);
          return content;
     }
}
